package zeno.project.springboot.controller.core;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import zeno.project.springboot.entity.User;
import zeno.project.springboot.entity.base.JsonResult;
import zeno.project.springboot.redis.RedisService;

import javax.annotation.Resource;
import java.util.List;

/**
 * redis的controller
 * 测试redis
 * @author zhiyong
 */
@RestController
@RequestMapping("/redis")
@Api(value = "Redis学习")
public class RedisController {
    private static final Logger logger = LoggerFactory.getLogger(RedisController.class);

    @Resource
    private RedisService redisService;

    @PostMapping("setStringData")
    @ApiOperation(value = "set字符串数据")
    public JsonResult<String> setStringData(@RequestParam(value = "key") String key, @RequestParam(value = "data") String data) {
        //测试redis的string类型
        redisService.setString(key, data);
        return new JsonResult<>(data);
    }

    @PostMapping("setObjectData")
    @ApiOperation(value = "set对象数据")
    public JsonResult<User> setObjectData(@RequestParam(value = "key") String key, @RequestBody User user) {
        // 如果是个实体，我们可以使用json工具转成json字符串，
        redisService.setString(key, JSON.toJSONString(user));
        return new JsonResult<>(user);
    }

    @GetMapping("getData")
    @ApiOperation(value = "get数据")
    public JsonResult<String> getData(@RequestParam(value = "key") String key) {
        return new JsonResult<>(JSON.toJSONString(redisService.getString(key)));
    }

    @PostMapping("setHashData")
    @ApiOperation(value = "set hash数据")
    public JsonResult<String> setHashData(@RequestParam(value = "key") String key, @RequestParam(value = "filedKey") String filedKey, @RequestBody User user) {
        //测试redis的hash类型
        redisService.setHash(key, filedKey, JSON.toJSONString(user));
        return new JsonResult<>("用户姓名：" + redisService.getHash(key,filedKey));
    }

    @GetMapping("getHashData")
    @ApiOperation(value = "get hash数据")
    public JsonResult<String> getHashData(@RequestParam(value = "key") String key, @RequestParam(value = "filedKey") String filedKey) {
        return new JsonResult<>(JSON.toJSONString(redisService.getHash(key, filedKey)));
    }

    @GetMapping("setGetListData")
    @ApiOperation(value = "setGetList hash数据")
    public Object setGetListData() {
        //测试redis的list类型
        redisService.setList("list", "football", true);
        redisService.setList("list", "basketball", true);
        List<String> valList = redisService.getList("list",0,-1);
        for(String value :valList){
            logger.info("list中有：{}", value);
        }
        return new JsonResult<>(valList);
    }
}
